package construction

import (
	"strconv"
	"strings"
)

/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

type Codec struct {

}

func Constructor1() Codec {
 	return Codec{}
}

// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
	var dfs func(node *TreeNode)
	sb:=strings.Builder{}
	dfs= func(node *TreeNode) {
		if node==nil{
			sb.WriteString("null,")
			return
		}
		sb.WriteString(strconv.Itoa(node.Val))
		sb.WriteString(",")
		dfs(node.Left)
		dfs(node.Right)
	}
	dfs(root)
	return sb.String()
}

// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
	ss:=strings.Split(data,",")
	var build func() *TreeNode
	build = func() *TreeNode {
		if ss[0]=="null"{
			ss=ss[1:]
			return nil
		}
		val,_:=strconv.Atoi(ss[0])
		ss=ss[1:]
		return &TreeNode{
			Val:   val,
			Left:  build(),
			Right: build(),
		}
	}
	return build()
}
